/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.planning;

import cn.ac.nercis.pes.common.constant.common.AssetConstants;
import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.component.spreadsheet.planning.TargetConfirmSheetView;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.mapper.project.SystemTargetViewMapper;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.planning.TargetConfirmView;
import cn.ac.nercis.pes.model.dto.target.EditApplyTargetDTO;
import cn.ac.nercis.pes.model.dto.target.LayerTargetDTO;
import cn.ac.nercis.pes.service.project.SystemProcessService;
import cn.ac.nercis.pes.service.project.SystemTargetService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;

/**
 * 标准指标管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class StandardTargetController implements Initializable {
    private static final String TITLE_FORMAT = "%s（基本指标）";

    @FXML
    private StackPane page;

    @FXML
    private Label titleLbl;
    @FXML
    private Button saveButton;
    @FXML
    private Button tmpSaveButton;

    @FXML
    private Button specialButton;
    @FXML
    private TargetConfirmSheetView sheetView;

    private final SystemTargetService systemTargetService;
    private final SystemProcessService systemProcessService;
    private final ExecutorService executor;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);

    private String currentSystemId;
    private LayerTargetDTO currentLayerTarget;

    public StandardTargetController() {
        this.systemTargetService = SpringUtils.getBean(SystemTargetService.class);
        this.systemProcessService = SpringUtils.getBean(SystemProcessService.class);
        this.executor = SpringUtils.getBean(ExecutorService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        specialButton.setGraphic(IconUtils.getGlyph("related-button-icon","btn-icon"));
        realTimeSaveManager.listenerSheetChange(this.sheetView);
    }

    public void initializeData(String systemId,LayerTargetDTO layerTarget){
        this.currentSystemId = systemId;
        this.currentLayerTarget = layerTarget;
        this.sheetView.initialize(systemId);

        this.titleLbl.setText(String.format(TITLE_FORMAT,currentLayerTarget.getName()));
        this.queryTargetList();
    }

    @FXML
    public void onTmpSave() {
        LogUtils.info(log, "执行暂存操作...");
        this.batchSave(false,false);
    }

    @FXML
    public void onFinishSave() {
        LogUtils.info(log, "执行保存操作...");
        this.batchSave(false,true);
    }

    @FXML
    public void onSpecialAction(){
        LogUtils.info(log, "执行进入特殊指标操作...");
        var targetView = AppStore.getEvaluationView(this.currentSystemId, TargetConfirmView.class);
        if(targetView.getController() instanceof TargetConfirmController controller){
            controller.gotoSpecialTarget();
        }
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        this.batchSave(true,false);
    }

    private void batchSave(boolean realTime,boolean finish){
        if(!this.sheetView.validate()){
            if(!realTime){
                AppUtils.showMessageDialog("以下标出的测评指标确认信息不能为空", MessageType.WARN,this.page);
            }
            return;
        }
        var targetData = this.sheetView.getModifyData().stream()
                .map(ut -> EditApplyTargetDTO.builder()
                        .id(ut.getId())
                        .systemId(ut.getSystemId())
                        .isApply(StringUtils.equals(ut.getIsApply(), AssetConstants.USE_TAG))
                        .reasons(ut.getReasons())
                        .build())
                .toList();
        if (!realTime && CollectionUtils.isEmpty(targetData)) {
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.SUCCESS).withMessage("保存成功")
                    .build().show();
            refreshFinishProcess(finish);
            return;
        }
        LogUtils.info(log, "指标保存前检查信息...");
        LogUtils.record(log, "请求数据:{}", targetData);
        CompletableFuture.supplyAsync(() -> this.systemTargetService.batchCheckRelatedTarget(targetData),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        saveApplyTarget(realTime,targetData,finish);
                    } else {
                        AlertDialog alertDialog = AlertDialog.builder()
                                .withMode(AlertMode.CONFIRM)
                                .withType(AlertType.WARN)
                                .withTitle("操作提示")
                                .withContent(res.getMsg())
                                .withContainer(this.page)
                                .build();
                        alertDialog.show((confirm) -> {
                            if (confirm) {
                                saveApplyTarget(realTime,targetData,finish);
                            }
                        });
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("指标是否适用变更前检查信息出错!", ex);
                    return null;
                });
    }

    private void saveApplyTarget(boolean realTime,List<EditApplyTargetDTO> layerTargets,boolean finish) {
        LogUtils.info(log, "保存指标是否适用信息...");
        LogUtils.record(log, "请求数据:{}", layerTargets);
        CompletableFuture.supplyAsync(() -> this.systemTargetService.batchModifyApplyTarget(layerTargets),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (!res.isSuccess()) {
                        if(realTime){
                            log.error("即时保存指标是否适用信息失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    } else {
                        if(!realTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                        refreshFinishProcess(finish);
                        this.queryTargetList();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("保存指标是否适用信息出错!", ex);
                    return null;
                });
    }

    private void refreshFinishProcess(boolean finish) {
        EvaluationModule currentModule = EvaluationModule.fromNameByTargetConfirm(currentLayerTarget.getName());
        FinishState state = finish ? FinishState.FINISH : FinishState.INCOMPLETE;
        CompletableFuture.supplyAsync(() -> systemProcessService.setSystemProcess(this.currentSystemId, currentModule, state),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        var targetView = AppStore.getEvaluationView(this.currentSystemId, TargetConfirmView.class);
                        if(targetView.getController() instanceof TargetConfirmController controller){
                            controller.refreshMenu(currentLayerTarget.getTargetId());
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("设置测评进度信息出错!", ex);
                    return null;
                });
    }

    private void queryTargetList() {
        LogUtils.info(log, "获取单元指标信息...");
        LogUtils.record(log, "请求数据，systemId:{}，filter:{}", this.currentSystemId, currentLayerTarget.getTargetId());
        CompletableFuture.supplyAsync(() -> this.systemTargetService.findUnitTarget(this.currentSystemId,
                        currentLayerTarget.getTargetId()),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    var data = res.stream()
                            .map(SystemTargetViewMapper.INSTANCE::toUnitTargetVO)
                            .toList();
                    sheetView.loadContent(data);
                }))
                .exceptionally((ex) -> {
                    log.error("获取单元指标信息出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL)
                            .withMessage("加载数据表内容失败！")
                            .build().show();
                    return null;
                });
    }

}